Page({
  data: {
    tabIndex: 1,
    petList: [],        // 当前展示的
    allPets: [],        // 原始完整列表
    searchKeyword: '',  // 搜索框关键字
    selectedPets: []
  },
  
  onCheckChange(e) {
    // 获取当前变化的复选框值
    const value = e.detail.value;
    
    // 创建两个数组的副本
    const allPets = [...this.data.allPets];
    const petList = [...this.data.petList];
    
    // 更新所有宠物的选中状态
    allPets.forEach(item => {
      item.checked = value.includes(item.id.toString());
    });
    
    // 更新当前显示的宠物列表
    petList.forEach(item => {
      item.checked = value.includes(item.id.toString());
    });
    
    this.setData({ allPets, petList });
    wx.setStorageSync('cart', allPets);
  },
  onShow() {
    const userInfo = wx.getStorageSync('userInfo');
  
    if (!userInfo || !userInfo.openid) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
  
    // 请求后端收藏数据
    wx.request({
      url: `http://localhost:3000/favorites/${userInfo.openid}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          const pets = res.data.data || [];
  
          const initialized = pets.map(pet => ({
            ...pet,
            id: pet.id.toString(), 
            checked: false // 初始化未选中
          }));
  
          this.setData({
            allPets: initialized,
            petList: initialized,
            searchKeyword: ''
          });
          wx.setStorageSync('cart', initialized); // 可选
        } else {
          wx.showToast({ title: '获取收藏失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
    onAdopt() {
    // 获取选中的宠物
    const selectedPets = this.data.petList.filter(item => item.checked);
    if(selectedPets.length >= 3) {
        wx.showToast({
          title: '一次性最多领养3只',
          icon: 'none'
        })
        return
    }
    if (selectedPets.length > 0) {
        const petsToPass = selectedPets.map(pet => ({
        id: pet.id,
        name: pet.name,
        price: pet.price,
        image: pet.img, // 将 img 映射为 image
        age: pet.age
        }));
        
        // 跳转到结算页面，并传递选中的宠物数据
        wx.navigateTo({
        url: `/pages/cart/checkout/checkout?pets=${encodeURIComponent(JSON.stringify(petsToPass))}`
        });
    } else {
        wx.showToast({
        title: '请先选择宠物',
        icon: 'none'
        });
    }
    },
    onDeleteItem(e) {
        const { id } = e.currentTarget.dataset;
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo || !userInfo.openid) {
          wx.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
      
        // 调用后端删除接口
        wx.request({
          url: 'http://localhost:3000/favorites',
          method: 'DELETE',
          header: { 'Content-Type': 'application/json' },
          data: {
            user_id: userInfo.openid,
            pet_id: id
          },
          success: (res) => {
            if (res.data.code === 200) {
              // 本地更新
              const newList = this.data.allPets.filter(item => item.id !== id);
              this.setData({
                allPets: newList,
                petList: newList.filter(p => p.name.toLowerCase().includes(this.data.searchKeyword))
              });
              wx.setStorageSync('cart', newList);
              wx.showToast({ title: '已删除', icon: 'success' });
            } else {
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '网络错误', icon: 'none' });
          }
        });
      },
  
      onClearCart() {
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo || !userInfo.openid) {
          wx.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
      
        wx.showModal({
          title: '确认清空',
          content: '确定要清空吗？',
          success: (res) => {
            if (res.confirm) {
              const petIds = this.data.allPets.map(pet => pet.id);
              wx.request({
                url: 'http://localhost:3000/favorites/batch',
                method: 'DELETE',
                header: { 'Content-Type': 'application/json' },
                data: {
                  user_id: userInfo.openid,
                  pet_ids: petIds
                },
                success: (res) => {
                  if (res.data.code === 200) {
                    this.setData({ petList: [], allPets: [] });
                    wx.setStorageSync('cart', []);
                    wx.showToast({ title: '已清空', icon: 'success' });
                  } else {
                    wx.showToast({ title: '清空失败', icon: 'none' });
                  }
                },
                fail: () => {
                  wx.showToast({ title: '网络错误', icon: 'none' });
                }
              });
            }
          }
        });
      },
  
  onGoToAdd() {
    wx.showToast({ title: '前往添加宠物', icon: 'none' });
    setTimeout(() => {
      wx.switchTab({ url: '/pages/index/index' });
    }, 500);
  },
  
  onGoToDetail(e) {
    const id = e.currentTarget.dataset.id;
    const pet = this.data.petList.find(item => item.id === id);
    if (!pet) return;
    wx.navigateTo({
      url: '/pages/pet-detail/pet-detail',
      success: (res) => res.eventChannel.emit('petData', { pet })
    });
  },
  
  onSearchInput(e) {
    const keyword = e.detail.value.trim().toLowerCase();
    const filtered = this.data.allPets.filter(pet =>
      pet.name.toLowerCase().includes(keyword)
    );
    this.setData({ searchKeyword: keyword, petList: filtered });
  },
  
  onTabChange(e) {
    const index = e.detail.index;
    const tabPages = [
      '/pages/index/index',
      '/pages/cart/cart',
      '/pages/map-pet/map-pet',
      '/pages/settings/settings'
    ];
    if (index === this.data.tabIndex) return;
    wx.switchTab({ url: tabPages[index] });
  }
});